package org.smart.access.utils;

public class SnowflakeIdWorker {

    // Epoch: 2004-12-03 13:14:00 UTC
    private final long epoch = 1102012800000L;

    private static final int WORKER_ID_BITS = 5;
    private static final int DATACENTER_ID_BITS = 5;
    private static final int SEQUENCE_BITS = 12;

    private static final long MAX_WORKER_ID = (1L << WORKER_ID_BITS) - 1;
    private static final long MAX_DATACENTER_ID = (1L << DATACENTER_ID_BITS) - 1;

    private static final int WORKER_ID_SHIFT = SEQUENCE_BITS;
    private static final int DATACENTER_ID_SHIFT = SEQUENCE_BITS + WORKER_ID_BITS;
    private static final int TIMESTAMP_LEFT_SHIFT = SEQUENCE_BITS + WORKER_ID_BITS + DATACENTER_ID_BITS;
    private static final long SEQUENCE_MASK = (1L << SEQUENCE_BITS) - 1;

    private final long workerId;
    private final long datacenterId;

    private long sequence = 0L;
    private long lastTimestamp = -1L;

    public SnowflakeIdWorker(long workerId, long datacenterId) {
        if (workerId < 0 || workerId > MAX_WORKER_ID) {
            throw new IllegalArgumentException("workerId must be between 0 and " + MAX_WORKER_ID);
        }
        if (datacenterId < 0 || datacenterId > MAX_DATACENTER_ID) {
            throw new IllegalArgumentException("datacenterId must be between 0 and " + MAX_DATACENTER_ID);
        }
        this.workerId = workerId;
        this.datacenterId = datacenterId;
    }

    public synchronized long nextId() {
        return nextId(System.currentTimeMillis());
    }

    /**
     * 生成下一个ID
     * 注意, 该方法本该为私有方法, 为了单元测试所以改为公开方法, 请勿在生成环境中使用
     *
     * @param timestamp 时间戳
     * @return ID
     */
    public synchronized long nextId(long timestamp) {
        if (timestamp < epoch) {
            throw new IllegalArgumentException("System clock is before epoch!");
        }

        if (timestamp < lastTimestamp) {
            long offset = lastTimestamp - timestamp;
            if (offset > 5) { // 容忍 5ms 内回拨
                throw new RuntimeException("Clock moved backwards: " + offset + " ms");
            }
            // 等待时钟追上
            while (System.currentTimeMillis() <= lastTimestamp) {
                try {
                    Thread.sleep(1);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                    throw new RuntimeException("Interrupted while waiting for clock to catch up", e);
                }
            }
            timestamp = System.currentTimeMillis();
        }

        if (lastTimestamp == timestamp) {
            sequence = (sequence + 1) & SEQUENCE_MASK;
            if (sequence == 0L) {
                // 序列号用完，等待下一毫秒
                while (System.currentTimeMillis() <= lastTimestamp) {
                    try {
                        Thread.sleep(1);
                    } catch (InterruptedException e) {
                        Thread.currentThread().interrupt();
                        throw new RuntimeException("Interrupted while waiting for next millisecond", e);
                    }
                }
                timestamp = System.currentTimeMillis();
            }
        } else {
            sequence = 0L; // 重置序列号
        }

        lastTimestamp = timestamp;

        return ((timestamp - epoch) << TIMESTAMP_LEFT_SHIFT)
                | (datacenterId << DATACENTER_ID_SHIFT)
                | (workerId << WORKER_ID_SHIFT)
                | sequence;
    }

    // ============= ID反解析 =============

    /**
     * 通过ID反解析生成时间戳
     *
     * @param id ID
     * @return 整型时间戳
     */
    public long parseTimestamp(long id) {
        return (id >>> TIMESTAMP_LEFT_SHIFT) + epoch;
    }

    /**
     * 通过ID反解析生成workerId
     *
     * @param id ID
     * @return workerId
     */
    public long parseWorkerId(long id) {
        return (id >>> WORKER_ID_SHIFT) & MAX_WORKER_ID;
    }

    /**
     * 通过ID反解析生成datacenterId
     *
     * @param id ID
     * @return datacenterId
     */
    public long parseDatacenterId(long id) {
        return (id >>> DATACENTER_ID_SHIFT) & MAX_DATACENTER_ID;
    }

    /**
     * 通过ID反解析生成序列号
     *
     * @param id ID
     * @return 序列号
     */
    public long parseSequence(long id) {
        return id & SEQUENCE_MASK;
    }
}
